package com.studyadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.studyadmin.dto.StuMsgSel;
import com.studyadmin.entity.Classes;
import com.studyadmin.entity.Role;
import com.studyadmin.entity.Student;
import com.studyadmin.mapper.RoleMapper;
import com.studyadmin.mapper.StudentMapper;
import com.studyadmin.service.StudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studyadmin.util.JsonUtil;
import com.studyadmin.util.RedisConstant;
import com.studyadmin.util.StringUtilsValue;
import com.studyadmin.dto.RegParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.studyadmin.util.EncryptUtils.desEncrypt;

/**
 * <p>
 * 学生表 服务实现类
 * </p>
 *
 * @author lyl
 * @since 2023-03-14
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired(required = false)
    StudentMapper studentMapper;
    @Autowired(required = false)
    private RedisTemplate<String, String> redisTemplate;

    @Autowired(required = false)
    private RoleMapper roleMapper;

    /**
     * 用于登录者的注册
     *
     * @param regParam 回传经过校验的参数
     * @return 返回数据JSONUtil
     */
    @Override
    public JsonUtil register(RegParam regParam) {
        JsonUtil jsonUtil = new JsonUtil();
        System.out.println("-=-=-="+regParam);
        if (regParam == null) {
            jsonUtil.setCode(1);
            jsonUtil.setMsg("参数不合法");
            return jsonUtil;
        }
        // 获取传递过来的表单参数
        String number = regParam.getStuNum();
        Integer sex = regParam.getSex();
        String name = regParam.getStuName();
        String email = regParam.getStuEmail();
        String password = regParam.getPassword();
        String passwordConfirm = regParam.getPasswordConfirm();
        String code = regParam.getCode();
        //对用户名进行敏感词过滤， 使用官方过滤 sensitive-word
        if(SensitiveWordHelper.contains(name)){
            jsonUtil.setCode(1);
            String listString = "";
            for (String s : SensitiveWordHelper.findAll(name)) {
                listString += s + "\t";
            }
//            System.out.println("zifu :"+listString);
            jsonUtil.setMsg("请替换用户名中以下敏感词："+listString);
            return jsonUtil;
        }



        if (StringUtils.isAnyBlank(email, password, passwordConfirm, code)) {
            // 非空
            jsonUtil.setCode(1);
            jsonUtil.setMsg("参数不合法");
            return jsonUtil;

        } else if (!StringUtilsValue.checkEmail(email)) {
            // 邮箱格式校验
            jsonUtil.setCode(1);
            jsonUtil.setMsg("邮箱格式不正确");
            return jsonUtil;
        } else if (!password.equals(passwordConfirm)) {
            jsonUtil.setCode(1);
            jsonUtil.setMsg("密码不一致");
            return jsonUtil;
        } else if (!StringUtilsValue.checkPassword(password) || code.length() != 6) {
            // 密码格式和验证码长度校验
            jsonUtil.setCode(1);
            jsonUtil.setMsg("参数不合法");
            return jsonUtil;
        }
        // 构造查询条件对象
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.select("stu_id");
        wrapper.eq("stu_email", email);
        wrapper.last("limit 1");
        // 查询用户，是否存在 邮箱是否被注册
        if (this.baseMapper.selectOne(wrapper) != null) {
            jsonUtil.setCode(1);
            jsonUtil.setMsg("邮箱已被注册");
            return jsonUtil;
        }

        // 获取正确的验证码
        String rightCode = redisTemplate.opsForValue().get(RedisConstant.EMAIL + email);
        if (!code.equals(rightCode)) {
            // 验证码比对
            jsonUtil.setCode(1);
            jsonUtil.setMsg("验证码错误");
            return jsonUtil;
        }
        // 删除验证码
        redisTemplate.delete(RedisConstant.EMAIL + email);
        // 注册用户
        Student student = new Student();
        student.setStuName(name);
        student.setSex(sex);
        student.setStuNum(number);
        student.setStuEmail(email);
        // 密码加密使用对称加密
        String p = null;
        try {
            //编码 进行加密
            p = desEncrypt(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        student.setPassword(p);
        if (this.baseMapper.insert(student) == 0) {
            jsonUtil.setCode(1);
            jsonUtil.setMsg("未知异常, 联系管理员");
            return jsonUtil;
        }
        Role role = new Role();
        role.setRoleCode("1");
        role.setRoleNum(number);
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.insert(role);

        jsonUtil.setCode(0);
        jsonUtil.setMsg("注册成功");
        return jsonUtil;
    }

    /**
     * 分页查询学生数据
     * @param page 分页数据
     * @param wrapper
     * @return
     */
    @Override
    public IPage pageForStu(IPage<Student> page, Wrapper wrapper) {

        return studentMapper.pageCC(page,wrapper);
    }

    @Override
    public JsonUtil stuMainSer(String stuNum) {
        JsonUtil jsonUtil = new JsonUtil();
        Student student = studentMapper.selectOne(
                new QueryWrapper<Student>()
                        .select("stu_num","stu_name","sex","password","avatar","stu_email","stu_state")
                        .eq("stu_num",stuNum)
                        .eq("del_flag",0)
        );
        jsonUtil.setCode(0);
        jsonUtil.setData(student);


        return jsonUtil;
    }


    /**
     * 修改信息
     * @param student
     * @return
     */
    @Override
    public JsonUtil updateStudentById(Student student) {
        JsonUtil jsonUtil = new JsonUtil();

        UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("stu_num", student.getStuNum())
                .set("sex", student.getSex())
                .set("stu_name", student.getStuName())
                .set("stu_email", student.getStuEmail())
                .set("update_time",LocalDateTime.now())
                ;
        int res=studentMapper.update(null, updateWrapper);
        if(res<0){
            jsonUtil.setCode(1);
            jsonUtil.setMsg("修改失败");
        }
        jsonUtil.setCode(0);
        jsonUtil.setMsg("修改成功");
        return jsonUtil;
    }

    @Override
    public JsonUtil updateStuImgUrlSer(Student student) {
        JsonUtil jsonUtil = new JsonUtil();

        UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("stu_num", student.getStuNum())
                .set("avatar", student.getAvatar());
        int resup=studentMapper.update(null, updateWrapper);
        if(resup<0){
            jsonUtil.setCode(1);
            jsonUtil.setMsg("修改失败");
        }
        jsonUtil.setCode(0);
        jsonUtil.setMsg("修改成功");
        return jsonUtil;

    }

    /**
     *学生发送的消息
     *
     * @return
     */
    @Override
    public JsonUtil stuSendMsgSer(String teaNum) {
//        List< Student > list=studentService.list();
//        JsonUtil jsonUtil = new JsonUtil();
//        jsonUtil.setCode(0);
//        jsonUtil.setData(list);
        //查询学生数据需要 stuName:'',
        //        //   stuNum:'', stuMsgSel
        JsonUtil jsonUtil = new JsonUtil();
        List<StuMsgSel> stuMsgSel=studentMapper.selSendMsg(teaNum);

        System.out.println("-=-=-=-=-=-"+stuMsgSel);

        jsonUtil.setCode(0);
        jsonUtil.setData(stuMsgSel);


        return jsonUtil;
    }


}
